package com.levi.exception;

import com.levi.enums.EnumUtil;
import com.levi.pojo.User;
import com.levi.vo.ResponseVo;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * @author shentong
 * @since 2022/3/23 9:31 PM
 */
@ControllerAdvice
public class RuntimeExceptionHandler {

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ResponseVo<User> handler(RuntimeException e) {
        return ResponseVo.error(EnumUtil.ERROR, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(UserLoginException.class)
    public ResponseVo<User> userLoginHandler() {
        return ResponseVo.error(EnumUtil.NEED_LOGIN);
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseVo bindResultHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        return ResponseVo.error(EnumUtil.PARAM_ERROR, "参数有误, " + Objects.requireNonNull(bindingResult.getFieldError()).getField() + " " + bindingResult.getFieldError().getDefaultMessage());
    }
}
